const { regClass, property } = Laya;

@regClass()
export class CamearCtr extends Laya.Script {
    //declare owner : Laya.Sprite3D;
    //declare owner : Laya.Sprite;

    @property(Laya.Sprite3D)
    declare target: Laya.Sprite3D;

    @property(Number)
    // 基础跟随距离
    public followDistance: number = 5;
    @property(Number)
    // 高度偏移量
    public heightOffset: number = 2;
    @property(Number)
    // 跟随平滑系数（0.1-0.3效果最佳）
    public smoothSpeed: number = 0.15;

    private _camera: Laya.Camera;

    @property(Laya.Vector3)
    private dir:Laya.Vector3;

    onStart(): void {
        this._camera = this.owner as Laya.Camera;
        console.log(this._camera.name)
        console.log(this.target.name)


        // 获取目标当前朝向
        const targetForward = new Laya.Vector3();
        this.target.transform.getForward(targetForward);
        Laya.Vector3.normalize(targetForward, targetForward);

        const targetPos = this.target.transform.position;
        const idealPos = new Laya.Vector3(
            //targetPos.x - targetForward.x * this.followDistance,
            targetPos.x,
            targetPos.y + this.heightOffset,
            targetPos.z + targetForward.z * this.followDistance
        );
        console.log("ilde,",idealPos.x,idealPos.y,idealPos.z)
    }

    onLateUpdate(): void {
        if (!this.target) return;

        // 获取目标当前朝向
        const targetForward = new Laya.Vector3();
        this.target.transform.getForward(targetForward);
        Laya.Vector3.normalize(targetForward, targetForward);

        // 计算理想相机位置（目标后方）
        const targetPos = this.target.transform.position;
        const idealPos = new Laya.Vector3(
            targetPos.x + targetForward.x * this.followDistance,
            targetPos.y + this.heightOffset,
            targetPos.z + targetForward.z * this.followDistance
        );
        
        // 平滑移动
        const currentPos = this._camera.transform.position;
        Laya.Vector3.lerp(currentPos, idealPos, this.smoothSpeed, currentPos);

        // 始终注视目标
        this._camera.transform.lookAt(targetPos, Laya.Vector3.Up);
        this._camera.transform.position =currentPos
    }

    //组件被激活后执行，此时所有节点和组件均已创建完毕，此方法只执行一次
    //onAwake(): void {}

    //组件被启用后执行，例如节点被添加到舞台后
    //onEnable(): void {}

    //组件被禁用时执行，例如从节点从舞台移除后
    //onDisable(): void {}

    //第一次执行update之前执行，只会执行一次
    //onStart(): void {}

    //手动调用节点销毁时执行
    //onDestroy(): void {}

    //每帧更新时执行，尽量不要在这里写大循环逻辑或者使用getComponent方法
    //onUpdate(): void {}

    //每帧更新时执行，在update之后执行，尽量不要在这里写大循环逻辑或者使用getComponent方法
    //onLateUpdate(): void {}

    //鼠标点击后执行。与交互相关的还有onMouseDown等十多个函数，具体请参阅文档。
    //onMouseClick(): void {}
}